<!-- eslint-disable regexp/use-ignore-case -->
<script lang="ts" setup>
import type { UnwrapRef } from 'vue';
import { ref } from 'vue';
import ExcelJS from 'exceljs';
import { Modal, message } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import { useUpload } from './useUpload';
import { useDownExcel } from './useDownExcel';
import { useColumn } from './useColumn';
import useUserStore from '@/store/modules/user';
import { getHoursByCompanyPage } from '@/api/modules/rbac/dcp/engineercertification_data';

const userStore = useUserStore();
const orgName = userStore.userOrgName;
const account = userStore.account;
const dataIsReady = ref(false);
const loading = ref<boolean>(false);
const data = ref<EAPI.engineerDataItem[]>([]);
const searchkeyword = ref('');
const total = ref<number>(0);
const pageSize = ref<number>(10);
const current = ref<number>(1);

async function getAllEngineerData() {
  data.value = [];
  loading.value = true;
  if (account === '管理员') {
    await getEngineerHoursByPage(current.value, pageSize.value).then((res: any) => {
      data.value = res.data.records;
      dataIsReady.value = true;
      total.value = res.data.total;
    }).finally(() => {
      loading.value = false;
    });
  }
  else {
    await getHoursByCompanyPage(current.value, pageSize.value, orgName).then((res: any) => {
      data.value = res.data.records;
      dataIsReady.value = true;
      total.value = res.data.total;
    }).finally(() => {
      loading.value = false;
    });
  }
}
// async function getAllEngineerData() {
//   data.value = [];
//   loading.value = true;
//   await getEngineerHoursByPage(current.value, pageSize.value).then((res: any) => {
//     data.value = res.data.records;
//     dataIsReady.value = true;
//     total.value = res.data.total;

//     // 计算每个人的复核工时总和
//     const reviewedHoursSum = data.value.reduce((acc: any, item: any) => {
//       if (acc[item.employeeId]) {
//         acc[item.employeeId] += item.reviewedHours;
//       }
//       else {
//         acc[item.employeeId] = item.reviewedHours;
//       }
//       return acc;
//     }, {});

//     // 打印每个人的复核工时总和
//     // eslint-disable-next-line no-console
//     console.log('每个人的复核工时总和:', reviewedHoursSum);
//   }).finally(() => {
//     loading.value = false;
//   });
// }
onMounted(async () => {
  getAllEngineerData();
});

const { columnsWH } = useColumn();
const codePattern = /^-?\d+(\.\d+)?$/;
async function onSearch() {
  if (codePattern.test(searchkeyword.value)) {
    try {
      const response: any = await getEngineerSearch({ employeeId: searchkeyword.value });
      if (response.data.length > 0) {
        data.value = response.data;
        total.value = response.data.length;
        if (total.value === 0) {
          message.success('没有查询到相关记录');
        }
        else {
          message.success('查询成功');
        }
      }
      else {
        message.error('未找到匹配的成员ID');
      }
    }
    catch (error) {
      console.error('按编码搜索失败:', error);
    }
  }
  else {
    try {
      const response: any = await getEngineerSearch({ employeeName: searchkeyword.value });
      if (response.data.length > 0) {
        data.value = response.data;
        total.value = response.data.length;
        if (total.value === 0) {
          message.success('没有查询到相关记录');
        }
        else {
          message.success('查询成功');
        }
      }
      else {
        message.error('未找到匹配的成员姓名或成员ID');
      }
    }
    catch (error) {
      console.error('按姓名搜索失败:', error);
    }
  }
}
const editableData: UnwrapRef<Record<string, any>> = reactive({});

// excel文件上传
const fileList = ref<any>([]);

// 移除文件
function handleRemove(file: any) {
  const index = fileList.value.findIndex((f: { uid: any }) => f.uid === file.uid);
  fileList.value.splice(index, 1);
}

// 阻止自动上传
function beforeUpload(file: any) {
  fileList.value = [];
  fileList.value.push(file);
  return false; // 阻止自动上传
}

// 手动上传
async function handleManualUpload() {
  if (fileList.value.length === 0) {
    message.error('请上传文件！');
    return;
  }
  fileList.value.forEach(async (file: any) => {
    // 判断文件类型
    if (useUpload().checkIfExcel(file.name || '')) {
      const formData = new FormData();
      formData.append('file', file);
      const reader = new FileReader();
      reader.onload = async (e) => {
        const buffer: any = e.target?.result;
        if (buffer) {
          const workbook = new ExcelJS.Workbook();
          await workbook.xlsx.load(buffer).then(async () => {
            const worksheet: any = workbook.getWorksheet(1);
            const headers: any[] = [];
            const flag = useUpload().checkWorkingHoursHeader(worksheet, headers);
            if (flag) {
              // clearEngineerData();
              await uploadEmployeehoursData(formData).then(() => {
                message.success('上传成功！');
                handleRemove(file);
                // 更新数据
                getAllEngineerData();
              })
                .catch(() => {
                  message.error('上传失败');
                  // 重新更新数据，将原先显示在页面的数据撤回
                  getAllEngineerData();
                });
            }
          });
        }
      };
      reader.readAsArrayBuffer(file);
    }
    else {
      message.error('请上传execl文件！');
    }
  });
}

// 清空数据库
// async function clearEngineerData() {
//   loading.value = true;
//   try {
//     await deleteEngineerAll();
//     getAllEngineerData();
//     message.success('数据库清空成功');
//   }
//   catch (error) {
//     message.error('清空数据库失败');
//   }
//   finally {
//     loading.value = false;
//   }
// }

// 删除单条
async function deleteSingleEngineerHours(id: number) {
  await deleteEngineerHours(id).then(() => {
    message.success('删除成功！');
    getAllEngineerData();
  });
}

function edit(id: number) {
  editableData[id] = cloneDeep(data?.value?.filter((item: { id: number }) => id === item.id)[0]);
}

async function save(id: number) {
  const newData = Object.assign(data?.value?.filter((item: { id: number }) => id === item.id)[0], editableData[id]);
  // 构建更新的数据对象
  newData.reviewedHours = Number.parseInt(newData.reviewedHours, 10);
  const updateData = {
    id: newData.id,
    employeeId: newData.employeeId,
    workMonth: newData.workMonth,
    employeeName: newData.employeeName,
    reviewedHours: newData.reviewedHours,
  };
  // 执行更新操作
  await updateEngineerHours(updateData).then(() => {
    message.success('修改成功');
  });
  // 删除 editableData 中的数据，完成编辑
  delete editableData[id];
}

function cancel(id: number) {
  delete editableData[id];
}

async function onDelete(id: number) {
  Modal.confirm({
    title: () => '确定要删除吗？',
    okText: () => '是的',
    okType: 'danger',
    cancelText: () => '取消',
    onOk() {
      data.value = data.value.filter((item: { id: number }) => item.id !== id);
      deleteSingleEngineerHours(id);
    },
  });
}

async function handleTableChange(pagination: any) {
  pageSize.value = pagination.pageSize;
  current.value = pagination.current;
  if (searchkeyword.value === '') {
    getAllEngineerData();
  }
}

// 选中
const selectedId = ref<any[]>([]);

function clearSelected() {
  selectedId.value = [];
}

const isSelected = computed(() => {
  return selectedId.value.length > 0;
});

// 全选功能
let flag = true;
function selectAll() {
  if (flag) {
    const allIds = data.value.map((item: { id: number }) => item.id);
    selectedId.value = allIds;
    flag = !flag;
  }
  else {
    selectedId.value = [];
    flag = !flag;
  }
}
const { auth } = useAuth();
function handleSelectionChange(selectedRowKeys: any[]) {
  selectedId.value = selectedRowKeys;
}
// 批量删除
async function clearChoose(selectedId: number[]) {
  loading.value = true;
  try {
    const res: any = await deleteChooseEngineerHours(selectedId);
    if (res) {
      message.success('删除成功');
      getAllEngineerData();
      clearSelected();
    }
  }
  catch (error) {
    message.error('删除失败');
  }
  finally {
    loading.value = false;
  }
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            研发人员工时导入
          </div>
          <a-button v-auth="'e-workingHours-edit'" type="link" @click="selectAll">
            全选
          </a-button>
          <a-input-search
            v-model:value="searchkeyword" v-auth="'e-workingHours-search'" placeholder="请输入完整的人员编码或姓名"
            enter-button style="width: 260px;" @search="onSearch"
          />
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <a-button v-if="isSelected" v-auth="'e-workingHours-search'" type="primary" @click="clearChoose(selectedId)">
            批量删除
          </a-button>
          <a-upload
            v-auth="'e-workingHours-upload'" :file-list="fileList" :before-upload="beforeUpload" name="file"
            :multiple="false" action="" accept=".xlsx, .xls" :on-remove="handleRemove"
          >
            <a-button>
              <upload-outlined /> 点击选择文件
            </a-button>
          </a-upload>
          <a-button v-auth="'e-workingHours-upload'" type="primary" @click="handleManualUpload">
            上传
          </a-button>
          <a-button v-auth="'e-workingHours-upload'" type="primary" @click="useDownExcel().downWorkingHoursExcel">
            下载模版
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="content">
      <a-table
        :columns="columnsWH" row-key="id" :data-source="data"
        :pagination="{ pageSize, showQuickJumper: true, total }" class="w-table" :scroll="{ x: 1024 }"
        :loading="loading"
        :row-selection="{ selectedRowKeys: selectedId, onChange: handleSelectionChange, getCheckboxProps: () => ({ disabled: !auth(['e-details-edit']) }) }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, text, record }">
          <template
            v-if="['workMonth', 'employeeName', 'employeeId', 'reviewedHours'].includes(column.dataIndex as string)"
          >
            <div>
              <a-input
                v-if="editableData[record.id]"
                v-model:value="editableData[record.id][column.dataIndex as string]" style="margin: -5px 0;"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <span v-if="editableData[record.id]">
                <a-typography-link @click="save(record.id)">保存</a-typography-link>

                <a @click="cancel(record.id)">取消</a>
              </span>
              <span v-else>
                <a-space>
                  <a @click="edit(record.id)">编辑</a>
                  <a v-if="data.length" @click="onDelete(record.id)">删除</a>
                </a-space>
              </span>
            </div>
          </template>
        </template>
      </a-table>
    </div>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    position: sticky;
    top: 0;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    background-color: #fff;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .content {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 95%;
    overflow: auto;
    overflow-y: auto;

    .w-table {
      flex-grow: 1;
      height: 100%;
      max-height: 100%;
      padding: 10px;
    }
  }
}

.editable-row-operations a {
  margin-right: 20px;
}
</style>
